package demo1;
/**
 * 
 * @author weiwei
 *
 */
import org.testng.ITestContext;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.testng.ITestResult;
import org.testng.TestListenerAdapter;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class FreemarkerDemo extends TestListenerAdapter{
	public int success;
	public int fail;
	@Override
	public void onFinish(ITestContext testContext) {

		List<ITestResult> fail_list = this.getFailedTests();
		List<ITestResult> pass_list = this.getPassedTests();
		
		
		success=pass_list.size();
		fail=fail_list.size();

		File file=new File("templates\\test1.html");
//		 //创建一个configuration对象
		 Configuration cfg = new Configuration();
		 //找到模板文件所在路径
		 try {
			cfg.setDirectoryForTemplateLoading(new File("./templates"));
			cfg.setDefaultEncoding("utf-8");
			 //创建模板对象
			 Template template =cfg.getTemplate("test1.ftl");
			 Map map=new HashMap();
			 int i=1;
			 int j=0;
			 for (ITestResult tr : pass_list) {
					String method_name = tr.getInstanceName() + "_" + tr.getName();
					map.put("p"+i,method_name );
					map.put("yn"+i, "PASS");
					i++;
				}
			 j+=i;
			 for (ITestResult tr : fail_list) {
					String method_name = tr.getInstanceName() + "_" + tr.getName();
					map.put("p"+j,method_name );
					map.put("yn"+j, "FAIL");
					j++;
				}
			 //数据集合

			 
			 map.put("sum",success+fail);
			 map.put("fail",fail);
			 
			 FileWriter out=new FileWriter("./templates/test1.html");
			 try {
				template.process(map, out);
			} catch (TemplateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			 if (null != out) {
				 out.flush();
			 }
			 out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 

	}
	
	
}
